#include "ExtLoader.h"


vector<UndefExtension*> * ExtLoader::GetExtPack()
{
	vector<UndefExtension*> * ExtPackage = new vector<UndefExtension*>
						  , * ExtLoaded;
	wxString ExtDir = config::var("EXTENSION_DIR");
	wxDir dir(ExtDir);

	if (!dir.IsOpened())
		return NULL;

	wxString filename;
#ifdef _WINDOWS
	wxRegEx reDll = wxT("(ext_)([a-zA-Z0-9_]+)(\\.dll)");
#else
	wxRegEx reDll = wxT("(ext_)([a-zA-Z0-9_]+)(\\.so)");
#endif
	bool cont = dir.GetFirst(&filename, wxEmptyString, wxDIR_DIRS);
	while ( cont )
	{
		wxString curDir = ExtDir + "/" + filename + "/dll/";
		if(wxDir::Exists(curDir))
		{
			wxArrayString fileList;
			wxDir::GetAllFiles(curDir, &fileList, wxEmptyString, wxDIR_FILES);
			for(size_t i = 0; i < fileList.size(); ++ i)
			{
				bool result;
				if(reDll.Matches(fileList[i]))
				{
					ExtLoaded = LoadExtension(fileList[i], result);
					if(result)
					{
						for(int j = 0; j < (int)ExtLoaded->size(); ++ j)
						{
							ExtPackage->push_back((*ExtLoaded)[j]);	
						}
					}
				}
			}
				
		}
		cont = dir.GetNext(&filename);
	}
	return ExtPackage;
}

vector<UndefExtension*> * ExtLoader::LoadExtension(wxString path, bool & result)
{
	vector<UndefExtension*> * ExtPackage = new vector<UndefExtension*>;
	result = false;
	wxDynamicLibrary * ext = new wxDynamicLibrary(path, wxDL_VERBATIM);
	UndefExtension * nExt;
	if(ext->IsLoaded())
	{
		NumOfExt GetExtensionsNum = (NumOfExt)ext->GetSymbol(wxT("GetExtensionsNum"), &result);
		NewExtension GetExtension = (NewExtension)ext->GetSymbol(wxT("GetExtension"), &result);
		if(result)
		{
			for(int i = 0; i < GetExtensionsNum(); ++ i)
			{
				nExt = (UndefExtension*)GetExtension(i);
				if(nExt->isok())
				{
					ExtPackage->push_back(nExt);
				}
			}
		
		}else
			wxLogError(_("'%s' isn't roto-extension."), path);
	}else wxLogError(_("Can't load dll plugin ..... %s"), path);
	return ExtPackage;
}
/*
void Load(wxString path)
{
	new wxDynamicLibrary(path);
}
*/
/*
void ExtLoader::SetCoreWindow(wxWindow * core)
{
	m_core = core;
}
*/